package com.rtf.framework.web.mvc.config.session.common;

import com.alibaba.fastjson.JSON;
import com.rtf.framework.common.exception.AppException;
import com.mzlion.easyokhttp.HttpClient;
import com.mzlion.easyokhttp.response.HttpResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 * http请求
 *
 * @author liuke
 * @date  2021/8/2 16:12
 * @version
*/
@Slf4j
public class AppUtilHttpClient {
    private static HttpClient HTTP_CLIENT = HttpClient.Instance;

    private static int CONNECT_TIMEOUT = 3;

    private static int READ_TIMEOUT = 5;

    static {
        // 设置连接超时和读超时时间
        HTTP_CLIENT.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS);
        HTTP_CLIENT.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS);
    }



    /**
     * 发起json请求
     *
     * @param uri
     * @param params
     * @return
     */
    public static HttpResponse sendJson(String uri, Map<String, Object> params) {
        uri = checkUri(uri);
        String jsonParm = JSON.toJSONString(params);
        // 发起post json请求
        HttpResponse httpResponse = HttpClient.textBody(uri).json(jsonParm).charset("utf-8").execute();
        if (!httpResponse.isSuccess()) {
            StringBuilder msg = new StringBuilder("远程执行:");
            msg.append(uri).append(jsonParm).append("异常：").append(httpResponse.getErrorMessage());
            log.error(msg.toString());
            throw new AppException(httpResponse.getErrorMessage(), httpResponse.getErrorCode() + "");
        }

        return httpResponse;
    }


    //校验uri
    private static String checkUri(String uri) {
        if (uri == null || uri.trim().length() == 0) {
            throw new IllegalArgumentException("uri不能为空");
        }

        // 如果uri不是以"/"开头
        if (!uri.startsWith("http")) {
            throw new IllegalArgumentException("uri格式不正确");

        }
        return uri;
    }
}
